from django.contrib import admin

from article.models import Article


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ['art_title', 'art_author', 'created_time', 'updated_time']

    def art_author(self, obj):
        return obj.author.author_name

    art_author.short_description = '作者'
    # 查找功能
    search_fields = (u"art_title", "author__author_name")

    def get_queryset(self, request):
        return super(ArticleAdmin, self).get_queryset(request).all().order_by("-id")

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(ArticleAdmin, self).get_search_results(request, queryset, search_term)
        try:
            search_term_as_int = int(search_term)
            queryset &= (self.model.objects.filter(gift_rule_id=search_term_as_int) |
                         self.model.objects.filter(user_id=search_term_as_int) |
                         self.model.objects.filter(activity_id=search_term))
        except:
            pass
        return queryset, use_distinct

    # 过滤器
    list_filter = ('created_time',)  # 指定列表过滤器，右边将会出现一个快捷的日期过滤选项，

    # 顶部时间过滤器
    date_hierarchy = ('created_time')

